﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CastleDemo1.Model;
using Castle.ActiveRecord;
namespace CastleDemo1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["Action"] != null && Request["PostId"] != null)
                {
                    if (Request.QueryString["Action"] == "Delete")
                    {
                        DeletePost(Request.QueryString["PostId"]);
                    }
                }
            }
        }
        protected override void OnPreRender(EventArgs e)
        {
            BindPostData();    
            base.OnPreRender(e);
        }
        private void OutPutScript(string key, string script)
        {
            ClientScript.RegisterStartupScript(this.GetType(), key, script,true);
        }
        private void DeletePost(string postId)
        {
            if (string.IsNullOrEmpty(postId))
            {
                throw new ArgumentNullException("PostId");
            }
            Post post = new Post();
            post.PostId = new Guid(postId);
            post.Delete();
        }
        private void DeletePostByTransaction(string postId)
        {
            if (string.IsNullOrEmpty(postId))
            {
                throw new ArgumentNullException("PostId");
            }
            Post post = new Post();
            post.PostId = new Guid(postId);
            post.Delete();
        }
        private void BindPostData()
        {
            repPost.DataSource = Post.FindAll().ToList<Post>();
            repPost.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Post post = new Post { PostContent = txtContent.Text, Title = txtTitle.Text, PublishDate = DateTime.Now, IsPublished = true, Author = "Me" };
            if (post.IsValid())
            {
                post.Create();
            }
            else
            {
                Response.Write(post.ValidationErrorMessages[0]);
            }
            TransactionScope trans = new TransactionScope();
        }
    }
}